package com.gitee.ed.example.druid;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.db.dialect.DialectName;
import cn.hutool.db.dialect.DriverNamePool;
import com.alibaba.druid.pool.DruidDataSource;
import org.sqlite.JDBC;

import javax.sql.DataSource;
import java.util.function.Consumer;

/**
 * Druid 数据源构建器
 *
 * @author hongda.li
 */
public class DruidDataSourceBuilder {

    private final DruidDataSource source = new DruidDataSource();

    private DruidDataSourceBuilder() {
    }

    public static DruidDataSourceBuilder newBuilder() {
        return new DruidDataSourceBuilder();
    }

    /**
     * 自定义配置
     *
     * @param consumer 自定义配置逻辑
     * @return 链式调用
     */
    public DruidDataSourceBuilder configure(Consumer<DruidDataSource> consumer) {
        consumer.accept(this.source);
        return this;
    }

    /**
     * 设置数据源的名称
     *
     * @param name 数据源名称
     * @return 链式调用
     */
    public DruidDataSourceBuilder setName(String name) {
        source.setName(name);
        return this;
    }

    /**
     * 设置数据源账号
     *
     * @param username 账号
     * @return 链式调用
     */
    public DruidDataSourceBuilder setUsername(String username) {
        source.setUsername(username);
        return this;
    }

    /**
     * 设置数据源密码
     *
     * @param password 密码
     * @return 链式调用
     */
    public DruidDataSourceBuilder setPassword(String password) {
        source.setPassword(password);
        return this;
    }

    /**
     * 设置数据源链接
     *
     * @param url 链接
     * @return 链式调用
     */
    public DruidDataSourceBuilder setUrl(String url) {
        source.setUrl(url);
        return this;
    }

    /**
     * 设置数据源驱动
     *
     * @param dialect 数据源驱动
     * @return 链式调用
     */
    public DruidDataSourceBuilder setDriver(DialectName dialect) {
        return switch (dialect) {
            case H2 -> this.setDriver(DriverNamePool.DRIVER_H2);
            case ORACLE -> this.setDriver(DriverNamePool.DRIVER_ORACLE);
            case MYSQL -> this.setDriver(DriverNamePool.DRIVER_MYSQL_V6);
            case SQLITE3 -> this.setDriver(DriverNamePool.DRIVER_SQLLITE3);
            case SQLSERVER -> this.setDriver(DriverNamePool.DRIVER_SQLSERVER);
            case POSTGRESQL -> this.setDriver(DriverNamePool.DRIVER_POSTGRESQL);
            default -> throw new UnsupportedOperationException();
        };
    }

    /**
     * 设置数据源驱动
     *
     * @param driver 数据源驱动
     * @return 链式调用
     */
    public DruidDataSourceBuilder setDriver(String driver) {
        source.setDriverClassName(driver);
        return this;
    }

    /**
     * 构建最终的数据源
     *
     * @return 最终数据源
     */
    public DataSource build() {
        // 自动创建SQLITE的父级目录
        if (CharSequenceUtil.startWith(source.getUrl(), JDBC.PREFIX)) {
            FileUtil.mkParentDirs(CharSequenceUtil.removePrefix(source.getUrl(), JDBC.PREFIX));
        }
        return source;
    }
}
